<?php


namespace Module\CmsAdminApi\Api\Controller;


use Illuminate\Routing\Controller;
use ModStart\Core\Exception\BizException;
use ModStart\Core\Input\InputPackage;
use ModStart\Core\Input\Response;
use Module\Cms\Type\CmsContentVerifyStatus;
use Module\Cms\Type\CmsModelContentStatus;
use Module\Cms\Util\CmsContentUtil;
use Module\Cms\Util\CmsModelUtil;

/**
 * @Api CMS对接API
 */
class ContentController extends Controller
{
    /**
     * @Api CMS添加
     * @ApiBodyParam ADMIN_API_KEY string 对接Key
     * @ApiBodyParam modelId int 模型ID
     * @ApiBodyParam catId int 栏目ID
     * @ApiBodyParam title string 标题
     * @ApiBodyParam summary string 描述
     * @ApiBodyParam cover string 封面图片
     * @ApiBodyParam seoTitle string SEO标题
     * @ApiBodyParam seoKeywords string SEO关键词
     * @ApiBodyParam seoDescription string SEO描述
     * @ApiBodyParam viewCount int 浏览量
     * @ApiBodyParam status int 是否显示 1显示 2隐藏
     * @ApiBodyParam verifyStatus int 审核状态 1待审核 2审核通过 3审核不通过
     * @ApiBodyParam author string 作者
     * @ApiBodyParam source string 来源
     * @ApiBodyParam content string 内容
     * @ApiBodyParam f_xxx string 模型特有字段
     * @ApiResponseData {
     *  "id":1
     * }
     */
    public function add()
    {
        $input = InputPackage::buildFromInput();
        $data = [];
        $data['modelId'] = $input->getInteger('modelId');
        $data['catId'] = $input->getInteger('catId');
        $data['title'] = $input->getTrimString('title');
        $data['summary'] = $input->getTrimString('summary');
        $data['cover'] = $input->getTrimString('cover');
        $data['seoTitle'] = $input->getTrimString('seoTitle');
        $data['seoKeywords'] = $input->getTrimString('seoKeywords');
        $data['seoDescription'] = $input->getTrimString('seoDescription');
        $data['viewCount'] = $input->getInteger('viewCount');
        $data['status'] = $input->getType('status', CmsModelContentStatus::class);
        $data['verifyStatus'] = $input->getType('verifyStatus', CmsContentVerifyStatus::class);
        $data['author'] = $input->getTrimString('author');
        $data['source'] = $input->getTrimString('source');
        $dataDetail = [];
        $dataDetail['content'] = $input->getRichContent('content');
        if (!empty($model['_customFields'])) {
            foreach ($model['_customFields'] as $field) {
                $dataDetail[$field['name']] = $input->getTrimString('f_' . $field['name']);
            }
        }
        $model = CmsModelUtil::get($data['modelId']);
        BizException::throwsIfEmpty('模型不存在', $model);
        $id = CmsContentUtil::insert($model, $data, $dataDetail);
        return Response::generateSuccessData([
            'id' => $id,
        ]);
    }
}
